package xx.iverson.video_manage.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.Comparator;
import java.util.UUID;

/**
 * xx.iverson.video_manage.util.VideoUploadUtil
 * 描述：
 * on 2025/11/3-下午3:05
 *
 * @author weijx
 */

@Component
public class VideoUploadUtil {

    @Value("${video.upload-dir:D:/video_manage/videos/}")
    private String uploadPath;

    @Value("${video.chunk-dir:D:/video_manage/chunks/}")
    private String tempDir;

    /**
     * 处理分片上传
     */
    public boolean processChunk(MultipartFile chunk, String fileMd5, Integer chunkIndex, Integer totalChunks) throws IOException {
        // 创建临时目录
        File tempDirFile = new File(tempDir + File.separator + fileMd5);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // 保存分片
        File chunkFile = new File(tempDirFile, chunkIndex.toString());
        chunk.transferTo(chunkFile);

        return true;
    }

    /**
     * 合并分片
     */
    public String mergeChunks(String fileMd5, String originalFileName) throws IOException {
        // 临时目录
        File tempDirFile = new File(tempDir + File.separator + fileMd5);
        File[] chunks = tempDirFile.listFiles();

        if (chunks == null || chunks.length == 0) {
            throw new IOException("没有找到分片文件");
        }

        // 生成存储文件名和路径
        String filePath = uploadPath + File.separator + originalFileName;

        // 确保上传目录存在
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 合并文件
        try (RandomAccessFile mergedFile = new RandomAccessFile(filePath, "rw")) {
            byte[] buffer = new byte[1024 * 1024];

            // 按分片索引排序
            Arrays.sort(chunks, Comparator.comparingInt(f -> Integer.parseInt(f.getName())));

            for (File chunkFile : chunks) {
                try (RandomAccessFile chunk = new RandomAccessFile(chunkFile, "r")) {
                    long chunkLength = chunk.length();
                    long bytesRead = 0;
                    while (bytesRead < chunkLength) {
                        int read = chunk.read(buffer);
                        if (read == -1) {
                            break;
                        }
                        mergedFile.write(buffer, 0, read);
                        bytesRead += read;
                    }
                }
                // 删除分片
                chunkFile.delete();
            }
        }

        // 删除临时目录
        tempDirFile.delete();

        return originalFileName;
    }

    /**
     * 检查分片是否存在
     */
    public boolean checkChunk(String fileMd5, Integer chunkIndex) {
        File chunkFile = new File(tempDir + File.separator + fileMd5 + File.separator + chunkIndex.toString());
        return chunkFile.exists();
    }

    /**
     * 获取已上传的分片列表
     */
    public Integer[] getUploadedChunks(String fileMd5) {
        File tempDirFile = new File(tempDir + File.separator + fileMd5);
        if (!tempDirFile.exists() || !tempDirFile.isDirectory()) {
            return new Integer[0];
        }

        File[] files = tempDirFile.listFiles((dir, name) -> name.matches("\\d+"));
        if (files == null) {
            return new Integer[0];
        }

        return Arrays.stream(files)
                .map(file -> Integer.parseInt(file.getName()))
                .toArray(Integer[]::new);
    }
}
